package com.api.weavernorth.action.uploadFile;

import com.weavernorth.util.FileUploadUtil;
import com.weavernorth.util.Logger4jUtil;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;

import static com.weavernorth.util.FileUploadUtil.checkFileSize;
import static com.weavernorth.util.FileUploadUtil.upload;

/**
 * @Author: bruseewang
 * @Package: com.api.weavernorth.action.uploadFile
 * @date: 2021/8/20 12:28
 * @description:
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private Logger log = Logger4jUtil.getLoggerByName("/action/api/uploadFile/");
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    /**
     * 上传数据及保存文件
     */
    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            log.info("Error: 表单必须包含 enctype=multipart/form-data");
//            PrintWriter writer = response.getWriter();
//            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
//            writer.flush();
            return;
        }
        // 上传路径相对当前应用的目录
        String uploadPath = getServletContext().getRealPath("/")  + UPLOAD_DIRECTORY;
        log.info("文件存储路径："+uploadPath);
        double fileSize=(double) request.getContentLength() / 1048576;
        log.info("上传文件的大小:"+fileSize+"M");
        int max_file_size= FileUploadUtil.MAX_FILE_SIZE / 1048576;//获取设置的文件上传的上限
        log.info("最大可上传文件:"+max_file_size+"M");
        if(checkFileSize(request.getContentLength(),max_file_size,"M")){
            request.setAttribute("message","文件大小超出上限,最大可上传40M");
        }else{
            String result=upload(uploadPath,request,log);
            String[] result_arr=result.split("\\|");
            String message_code=result_arr[0];
            String message=result_arr[1];
            if(message_code.equals("0")){
                request.setAttribute("message","文件上传成功!");
            }else{
                request.setAttribute("message",message);
            }
        }
        log.info("跳转页面到/weavernorth/message.jsp");
        log.info("request参数值："+request.getAttribute("message"));
        Runtime.getRuntime().exec("chmod 777 -R " + uploadPath);//设置读写权限
        // 跳转到 message.jsp
        getServletContext().getRequestDispatcher("/weavernorth/message.jsp").forward(
                request, response);
    }
}
